package com.cicadasmall.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cicadasmall.common.base.BaseService;
import com.cicadasmall.data.domain.PositionDO;
import com.cicadasmall.data.domain.UserPositionDO;
import com.cicadasmall.data.mapper.SysUserPositionMapper;
import com.cicadasmall.system.service.IPositionService;
import com.cicadasmall.system.service.IUserPositionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 用户部门关联表 service impl class
 * </p>
 *
 * @author westboy
 * @date 2019-08-21
 */
@Service
public class UserPositionServiceImpl extends BaseService<SysUserPositionMapper, UserPositionDO> implements IUserPositionService {
    @Autowired
    private IPositionService positionService;


    @Override
    public List<UserPositionDO> findByUserId(Integer uid) {
        return baseMapper.selectList(getLambdaQueryWrapper().eq(UserPositionDO::getUid, uid));
    }


    @Override
    public void updateUserPosition(Integer uid, List<String> postIds) {
        if (CollectionUtil.isNotEmpty(postIds)) {
            LambdaQueryWrapper lambdaQueryWrapper = getLambdaQueryWrapper().eq(UserPositionDO::getUid, uid);
            Integer count = baseMapper.selectCount(lambdaQueryWrapper);

            if (count > 0) {
                baseMapper.delete(lambdaQueryWrapper);
            }

            postIds.forEach(postId -> {
                PositionDO position = positionService.getById(postId);
                if (position != null) {
                    UserPositionDO userPosition = new UserPositionDO();
                    userPosition.setPostId(position.getId());
                    userPosition.setUid(uid);
                    baseMapper.insert(userPosition);
                }
            });
        }
    }
}
